<?php
/**
 * Created by PhpStorm.
 * User: 96151
 * Date: 2019/3/5
 * Time: 11:43
 */

namespace app\common\service\spider;

use app\common\service\swooleJobs\BookJobs;
use QL\QueryList;

class QuShu
{
    public static $host = "http://www.qushuba.com/";

    /**
     * 初始化小说配置
     */
    public function format_book_list()
    {
        // 初始化程序处理
        for ( $i = 0; $i < 40000; $i ++ ){
            $url = $this->get_url( $i );
            BookJobs::QuShuFormatJobs( $url );
        }
    }

    /**
     * 获取一个完整路径
     */
    public function get_url( $i )
    {
        return self::$host."shu{$i}/";
    }

    /**
     * 获取小说信息列表
     */
    public function get_content( $url )
    {
        $html = @file_get_contents( $url );

        if ( strpos( $html, "您搜索的小说地址已换" ) || !$html  ){
            return false;
        }

        $html = $this->handleGbkPage( $html );


        $ql  = (new QueryList())->html( $html );

        // 标题
        $title = $ql->find("h1")->text();

        // 获取作者
        $author = $ql->find("h1")->next()->text();
        $author = explode( "：", $author );
        $author = $author[1];

        // 获取最后更新时间
        $last_time = $ql->find("h1")->next()->next()->next()->text();
        $last_update_time = explode( "：", $last_time );
        $last_update_time = trim( str_replace(  array( "连载中", "完结"),"", $last_update_time[1] ) );

        // 获取是否完结
        $is_over = 0;

        if ( strpos( $last_time, "完结") !== false ){
            $is_over = 1;
        }

        // 获取封面
        $cover = $ql->find("#fmimg")->find("img")->src;

        // 获取简介
        $summary = $ql->find( "#intro")->text();

        $list = $ql->
            rules( [
                "url" => array( "dd>a", "href"),
                "title" => array( "dd", "text")
            ] )
            ->query()->encoding( "gbk",'UTF-8')->getData();
        $list = $list->all();

        foreach ( $list as &$value ){
            $value['url'] = $url.$value['url'];
        }

        $book_info = array(
            "title" => $title,
            "author" => $author,
            "last_update_time" => $last_update_time,
            "is_over" => $is_over,
            "cover" => $cover,
            "summary" => $summary,
            "url"     => $url,
            "list" => $list
        );
        return $book_info;
    }

    public function handleGbkPage( $html )
    {
        $html = mb_convert_encoding($html, 'UTF-8', 'GBK');
        $html = preg_replace('/charset=(gb2312|gbk)/is', 'charset=utf-8', $html); // 必须将 <meta/> 中 charset=* 替换为 utf-8，不然 phpQuery 不能解析标签

        return $html;
    }





}